<template>
    <div class="tabbar_container">
        <div class="content_card">
            <div class="left_card">
                <div class="left_title">底部导航设置</div>
                <div class="left_title_tip">最少添加2个导航入口，最多添加5个导航入口，支持调整导航顺序。</div>
                <div class="left_content">
                    <el-form ref="formRef" :model="form" label-width="auto" :disabled="!state.authSave">
                        <div class="form_item_card" v-for="(item, index) in form.options" :key="index">
                            <div
                                class="icon_btn_box"
                                :style="`grid-template-columns: repeat(${
                                    form.options.length === 1 ? 1 : [0, form.options.length - 1].includes(index) ? 2 : 3
                                }, 1fr)`">
                                <el-icon v-if="index !== 0" class="top_btn" @click="onTop(index)"><Top /></el-icon>
                                <el-icon
                                    v-if="index !== form.options.length - 1"
                                    class="bottom_btn"
                                    @click="onBottom(index)"
                                    ><Bottom
                                /></el-icon>
                                <el-tooltip
                                    effect="dark"
                                    content="该导航为首页，不支持删除。"
                                    placement="top"
                                    :disabled="item.isHomePage !== 1">
                                    <span>
                                        <el-popconfirm
                                            title="你确定要删除吗？"
                                            width="200"
                                            :icon="WarningFilled"
                                            icon-color="#faad14"
                                            :disabled="item.isHomePage === 1"
                                            @confirm="onDelete(index)">
                                            <template #reference>
                                                <el-icon
                                                    :class="['delete_btn', item.isHomePage === 1 ? 'disabled' : '']"
                                                    ><Delete
                                                /></el-icon>
                                            </template>
                                        </el-popconfirm>
                                    </span>
                                </el-tooltip>
                            </div>
                            <el-form-item label="导航名称" :prop="`options.${index}.name`" :rules="rules.name">
                                <el-input
                                    v-model="form.options[index].name"
                                    class="input_width_294"
                                    maxlength="5"
                                    clearable
                                    placeholder="不超过5个字" />
                            </el-form-item>

                            <el-form-item label="导航图标" :prop="`options.${index}.imgurl`" :rules="rules.imgurl">
                                <div class="upload_form_item">
                                    <el-form-item>
                                        <div class="upload_box">
                                            <div class="upload_btn">
                                                <el-image class="upload_img" :src="item.imgurl[0]" fit="cover">
                                                    <template #error>
                                                        <el-icon class="upload_img_placeholder"><Plus /></el-icon>
                                                    </template>
                                                    <template #placeholder>
                                                        <el-icon class="upload_img_placeholder"><Plus /></el-icon>
                                                    </template>
                                                </el-image>
                                            </div>
                                            <div class="upload_name">选中</div>
                                        </div>
                                    </el-form-item>
                                    <el-form-item>
                                        <div class="upload_box">
                                            <div class="upload_btn">
                                                <el-image class="upload_img" :src="item.imgurl[1]" fit="cover">
                                                    <template #error>
                                                        <el-icon class="upload_img_placeholder"><Plus /></el-icon>
                                                    </template>
                                                    <template #placeholder>
                                                        <el-icon class="upload_img_placeholder"><Plus /></el-icon>
                                                    </template>
                                                </el-image>
                                            </div>
                                            <div class="upload_name">未选中</div>
                                        </div>
                                    </el-form-item>
                                    <div class="select_icon_btn">
                                        <span @click="onOpenDialog(item, index)">选择图标</span>
                                    </div>
                                </div>
                            </el-form-item>
                            <div class="width_373">
                                <MutualChoose
                                    @sendParam="getParamList($event, index)"
                                    :typeList="state.typeList"
                                    :category="categoryList"
                                    :row="item"
                                    :isHomePage="item.isHomePage"
                                    :id="`options.${index}.id`"
                                    :openimg="`options.${index}.openimg`"
                                    :url="`options.${index}.url`"
                                    :mutual="`options.${index}.mutual`"
                                    :appId="`options.${index}.appId`" />
                            </div>
                        </div>
                        <div class="add_nav">
                            <el-tooltip
                                effect="dark"
                                content="最多添加5个导航。"
                                placement="top"
                                :disabled="form.options.length !== 5">
                                <span>
                                    <el-button
                                        type="primary"
                                        plain
                                        @click="onAddNav"
                                        :disabled="form.options.length === 5"
                                        >添加导航</el-button
                                    >
                                </span>
                            </el-tooltip>
                        </div>
                    </el-form>
                </div>
            </div>
            <div class="right_card">
                <div class="preview_box">
                    <div class="top">
                        <div class="time">10:00</div>
                        <div class="icons">
                            <img
                                src=""
                                alt="" />
                            <img
                                src=""
                                alt="" />
                            <img
                                src=""
                                alt="" />
                        </div>
                    </div>
                    <div class="nav_box">
                        <div class="nav_title">{{ state.shopName }}</div>
                        <div class="nav_img"><img src="@/assets/imgs/mall/decorate/more.png" alt="" /></div>
                    </div>
                    <div class="main_box">
                        <div class="main_img">
                            <img src="@/assets/imgs/mall/decorate/empty.png" alt="" />
                        </div>
                        <div class="main_desc">一大波商品正在来的路上…</div>
                    </div>
                    <div class="footer_box">
                        <div class="tabbar_item" v-for="item in form.options" :key="item.name">
                            <div class="tabbar_img_box">
                                <el-image
                                    class="tabbar_img"
                                    :src="item.imgurl[item.isHomePage == 1 ? 0 : 1]"
                                    fit="cover">
                                    <template #error>
                                        <el-icon class="tabbar_img_error"><icon-picture /></el-icon>
                                    </template>
                                </el-image>
                            </div>
                            <div class="tabbar_name">{{ item.name }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer_card" v-auth="'decorate_tabBar:save'">
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>

        <!-- 选择图标弹窗 -->
        <div class="icon_dialog">
            <el-dialog v-model="state.show" title="选择图标" width="600px">
                <div class="icon_dialog_content">
                    <div
                        v-for="item in state.imgList"
                        :class="['icon_item', item.bright === state.activeBright ? 'active' : '']"
                        :key="item.bright"
                        @click="onSelect(item)">
                        <div class="icon_item_img">
                            <el-image class="icon_img" :src="item.dark" fit="cover">
                                <template #error>
                                    <el-icon class="icon_img_error"><icon-picture /></el-icon>
                                </template>
                            </el-image>
                            <el-image class="icon_img" :src="item.bright" fit="cover">
                                <template #error>
                                    <el-icon class="icon_img_error"><icon-picture /></el-icon>
                                </template>
                            </el-image>
                        </div>
                        <div :class="['icon_item_name', item.bright === state.activeBright ? 'active' : '']">
                            {{ item.name }}
                        </div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="state.show = false">取消</el-button>
                        <el-button type="primary" @click="onConfirm(state.activeData)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import MutualChoose from '@/components/MutualChoose.vue';
import request from '@/request';
import { getGoodsCategoryListHook } from '@/hooks/goods';
import store from '@/store';
import { setLayout, resetLayout } from '@/hooks/layout';
import { Picture as IconPicture, Plus, WarningFilled } from '@element-plus/icons-vue';
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;

const state = reactive({
    // 店铺名称
    shopName: '',
    show: false,
    // 选择图标弹窗，图片列表
    imgList: [],
    // 当前设置导航的索引
    index: 0,
    // 当前选中的图标
    activeName: '首页',
    activeData: {},
    typeList: [],
    authSave: permissions.has('decorate_tabBar:save')
});

const formRef = ref(null);
const form = reactive({
    id: 1, //导航记录ID
    options: [] //导航数据
});
const rules = reactive({
    required: [{ required: true, message: '该字段必填', trigger: 'blur' }],
    imgurl: [{ required: true, message: '请选择导航图标', trigger: 'change' }],
    name: [{ required: true, message: '导航名称不能为空', trigger: 'blur' }],
    mutual: [{ required: true, message: '交互类型不能为空', trigger: 'change' }]
});
const onAddNav = () => {
    form.options.push({
        name: '',
        mutual: '',
        page: '',
        imgurl: [],
        isHomePage: 2,
        id: '',
        chooseName: ''
    });
};
const onSubmit = () => {
    if (form.options.length < 2) {
        ElMessage.error('底部导航最少添加2个');
        return;
    }
    formRef.value.validate(async valid => {
        if (valid) {
            await request('saveTabBarInfo', form);
            ElMessage.success('保存成功');
        }
    });
};
/* *******************************上移/下移/删除******************************* */
const onTop = index => {
    form.options.splice(index - 1, 0, form.options.splice(index, 1)[0]);
};
const onBottom = index => {
    form.options.splice(index + 1, 0, form.options.splice(index, 1)[0]);
};
const onDelete = index => {
    form.options.splice(index, 1);
};
/* *******************************上移/下移/删除******************************* */
const categoryList = ref([]);
const getGoodsCategoryList = async () => {
    if (categoryList.value.length === 0) {
        const data = await getGoodsCategoryListHook({ page: 1, perPage: 999 });
        form.options.forEach(item => {
            if (item.mutual === 4) {
                // 分组全部被删除
                if (data.list.length === 0) {
                    item.id = '';
                } else {
                    const obj = data.list.find(el => el.id === item.id);
                    // 如果当前选择的分组被删除，默认选中第一个
                    if (!obj) item.id = data.list[0].id;
                }
            }
        }) && getGoodsCategoryList();
        categoryList.value = data.list;
    }
};
const getParamList = async (v, index) => {
    form.options[index].chooseName = v.chooseName;
    form.options[index].id = v.id;
    form.options[index].url = v.url;
    form.options[index].mutual = v.mutual;
    form.options[index].page = v.page;
    if (v.mutual === 4) {
        getGoodsCategoryList();
        formRef.value.validateField(`options.${index}.id`);
    }
    if (v.mutual === 19) {
        form.options[index].openimg = v.openimg;
        formRef.value.validateField(`options.${index}.openimg`);
    }
    if (v.mutual == 14) {
        form.options[index].appId = v.appId;
    }
    formRef.value.validateField(`options.${index}.url`);
};
/* *******************************选择图标******************************* */
// 获取图标列表
const getTabBarImgList = async () => {
    const { data } = await request('getTabBarImgList');
    state.imgList = data || [];
    state.show = true;
};
const onOpenDialog = (item, index) => {
    if (!state.authSave) return;
    state.index = index;
    state.activeBright = item.imgurl[0];
    if (state.imgList.length > 0) {
        state.show = true;
    } else {
        getTabBarImgList();
    }
};
const onSelect = item => {
    state.activeBright = item.bright;
    state.activeData = item;
};
// 确定
const onConfirm = ({ name, bright, dark }) => {
    form.options[state.index].imgurl = [bright, dark];
    state.show = false;
    formRef.value.validateField(`options.${state.index}.imgurl`, (isValid, invalidFields) => {});
};
/* *******************************选择图标******************************* */
const getTypeList = async () => {
    const { data } = await request('templateMutual', { channel: 'navigation' });
    state.typeList = data || [];
};
/* 获取 tabBar info */
const getTabBarInfo = async () => {
    const { data } = await request('getTabBarInfo');
    form.id = data.id;
    form.options = data.options || [];
    // 是否有选择商品分组，有就调取获取商品分组列表接口
    form.options.some(item => item.mutual === 4) && getGoodsCategoryList();
};
onMounted(() => {
    const { shopList, shopId } = useAuth;
    state.shopName = shopList.find(item => item.shopId === shopId).shopName;
    setLayout();
    getTabBarInfo();
    getTypeList();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss" src="./index.scss" scoped></style>
